<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 新用户统计
 * Class Consumer
 */
class Consumer extends MY_Controller {

    /**
     * @var ConsumerOrderModel
     */
    public $mOrder = null;
    /**
     * @var ConsumerUserModel
     */
    public $mConsumer = null;

	public function __construct(){
		parent::__construct();
		$this->loadModel('ConsumerOrderModel', 'mOrder', 'consumer');
		$this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
	}
	
	/**
	 * 首页
	 */
	public function index(){
        $status = $this->mOrder->status();
        unset($status['']);
        unset($status['1']);
        unset($status['2']);
        $t = dateFormat(time());
        $s = strtotime($t);
        // 新增用户数
        // 首次下单数
        // 下单用户数
        // 订单总数量
        // 单客价
        // 总金额
        // 售后订单数
        // 售后订单总金额数
        $data = array(
            'order' => $this->countNewUserOrders($s),
            'time' => $t,
            'status' => $status,
        );
		$this->view('statistics/consumer', $data, 'datatable,datepicker,select2');
	}

	public function detail(){
        $s = trim(post('time'));
        $s = strtotime($s);
        $data = $this->countNewUserOrders($s);
        $this->ajaxReturn(1, '', $data);
    }

    /**
     * 新用户下单信息
     * @param $s        string      当天时间
     * @return array
     */
	private function getDetail($s){
        $status = post('status');
        if (!empty($status)){
            if (!is_array($status)){
                $status = explode(',', $status);
            }
            if (in_array('6', $status)){
                $status[] = 7;
            }
            $this->db->where_in('status', $status);
        }
        $e = strtotime('+1 day', $s);
        // 首次下单数
        $this->db
            ->where('addtime >= ' . $s)
            ->where('addtime < ' . $e)
            ->where('consumer_id not in (SELECT consumer_id from consumer_order where addtime < ' . $s . ')');
        $first = $this->mOrder->count($this->mOrder->tbOrder);

        if (!empty($status)){
            $this->db->where_in('o.status', $status);
        }
        $this->db->select('count(DISTINCT o.consumer_id) as consumer,count(o.id) as total,SUM( IF(o.status = 6 OR o.status= 7 ,1 ,0)) AS close_total,
            sum(o.reality_amount) as reality_amount,count(s.id) as service,sum(s.refund_amount) as refund_amount')
            ->join($this->mOrder->tbOrderService.' s', 's.order_id=o.id and s.status = 2', 'left')
            ->where('o.addtime >= '.$s)
            ->where('o.addtime < '.$e);
        $order = $this->mOrder->getOne($this->mOrder->tbOrder.' o');
        $order['total_consumer'] = $this->mConsumer->getTotalConsumer($s); // 新增用户数
        $order['reality_amount'] = isset($order['reality_amount']) ? $order['reality_amount'] : '0';
        $order['refund_amount'] = isset($order['refund_amount']) ? $order['refund_amount'] : '0';
        $order['single_price'] = $order['total'] > 0 ?  sprintf('%.2f',$order['reality_amount'] / $order['consumer']) : 0;
        $order['first'] = $first;
        return $order;
    }

    /**
     * 统计新用户数
     * @param $s
     * @return array
     */
    private function countNewUserOrders($s){

	    $e = strtotime('+1 day', $s);
	    //注册新用户数
        if ($s){
            $this->db->where('addtime >= '.$s);
            $this->db->where('addtime < '.$e);
        }
        $this->db->where(array('status >' => 0));
        $total_consumer =  $this->db->count_all_results('consumer');

        //获取在指定时间之前未下过单的用户
        $this->db->select("u.id");
        $this->db->from("consumer u");
        $this->db->join("consumer_order co","u.id = co.consumer_id AND co.merchant_take_time < ".$s,"left");
        $this->db->WHERE("co.id is NULL");
        $this->db->group_by("u.id");

        $temp = $this->db->get_compiled_select();
        $this->db->reset_query();
        //新用户订单总量,首次下单用户数,新用户客单价,新用户订单总额,新用户实付订单金额
        $this->db->select("COUNT(co.id) as total_order,
                            COUNT(DISTINCT co.consumer_id) as total_user,
                            IFNULL(SUM(co.total_amount),0) as total_amount,
                            IFNULL(SUM(co.reality_amount),0) as reality_amount,
                            IFNULL(TRUNCATE(SUM(co.reality_amount)/COUNT(co.id),2),0) as single_amount");
        $this->db->from("consumer_order co");
        $this->db->join("(".$temp.") te",'co.consumer_id=te.id');
        $this->db->where("co.consumer_id in (".$temp.")");
        $this->db->where("co.merchant_take_time >= ".$s);
        $this->db->where("co.merchant_take_time < ".$e);
        $this->db->where_in("co.status",[3,4,5,6]);
        $data = $this->db->get()->row_array();

        //新用户关闭订单数
        $this->db->reset_query();
        $this->db->select("COUNT(co.id) as close_order");
        $this->db->from("consumer_order co");
        $this->db->join("(".$temp.") te",'co.consumer_id=te.id');
        $this->db->where("co.addtime >= ".$s);
        $this->db->where("co.addtime < ".$e);
        $this->db->where_in("co.status",[7,8]);
        $data2 = $this->db->get()->row_array();
        $data['close_order']=$data2['close_order'];
        $data['total_consumer']=$total_consumer;
        return $data;
    }


    /**
     * 获取订单详情列表
     */
    public function getList(){
        $data = $this->newlists();
        //$this->db->last_query();
        foreach ($data['data'] as $k=>$v){
            $data['aaData'][$k][] = '';
            $data['aaData'][$k][] = $v['id'];
            $data['aaData'][$k][] = $v['code'];
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = $v['product_amount'];
            $shipping_fee = isset($v['shipping_fee']) ? $v['shipping_fee'] : 0;
            $data['aaData'][$k][] = $shipping_fee;
            $data['aaData'][$k][] = $v['reality_amount'];
            $data['aaData'][$k][] = $v['discount']; // 优惠金额
            $data['aaData'][$k][] = dateFormat($v['addtime'], true);
            if ($v['expense_type'] == 2) {
                $data['aaData'][$k][] = $this->mOrder->storeStatus($v['status'], true);
            } else {
                $data['aaData'][$k][] = $this->mOrder->status($v['status'], true);
            }
            $btnConfig = adminCreateBtn(array(
                'label' => '查看',
                'attr' => array(
                    'href' => getUrl('order/home/details?id='.$v['id']),
                    'class' => 'btn green-stripe btn-xs default'
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'order',
                    'key' => 'home-details'
                )
            ));
            $data['aaData'][$k][] = $btnConfig;
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 新用户列表
     */
    public function getNewUserList(){
        $data = $this->newUserlist();
        foreach ($data['data'] as $k=>$v){
            $img = isset($v['portrait']) ? getImage($v['portrait'], 'xs') : getDefaultPortrait();
            $data['aaData'][$k][] = '<img width="50px" src="'.$img.'" />';
            $data['aaData'][$k][] = $v['nickname']?$v['nickname']:'暂无昵称';
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = isset($v['realname']) ? $v['realname'] : '暂无';
            $data['aaData'][$k][] = $v['balance'];
            $data['aaData'][$k][] = $v['gender'] ? $this->mConsumer->getGender($v['gender']) : '保密';
            $data['aaData'][$k][] = dateFormat($v['addtime'],false);
            $data['aaData'][$k][] = isset($v['last_login_time']) ? date('Y-m-d H:i:s',$v['last_login_time']):'尚未登录';
            $btnConfig = adminCreateBtn(array(
                'label' => ' 详情',
//                'icon' => '<i class="fa fa-file-o"></i>',
                'attr' => array(
                    'href' => getUrl('member/consumer/details?id='.$v['id']),
                    'class' => 'btn btn-xs green-stripe default',
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'member',
                    'key' => 'consumer-details'
                )
            ));
            $data['aaData'][$k][] = $btnConfig;
        }

        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 首单用户
     */
    public function getFirstUserlist(){
        $data = $this->firstUserlist();
        foreach ($data['data'] as $k=>$v){
            $img = isset($v['portrait']) ? getImage($v['portrait'], 'xs') : getDefaultPortrait();
            $data['aaData'][$k][] = '<img width="50px" src="'.$img.'" />';
            $data['aaData'][$k][] = $v['nickname']?$v['nickname']:'暂无昵称';
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = isset($v['realname']) ? $v['realname'] : '暂无';
            $data['aaData'][$k][] = $v['balance'];
            $data['aaData'][$k][] = $v['gender'] ? $this->mConsumer->getGender($v['gender']) : '保密';
            $data['aaData'][$k][] = dateFormat($v['addtime'],false);
            $data['aaData'][$k][] = date('Y-m-d H:i:s',$v['orderTime']);
            $btnConfig = adminCreateBtn(array(
                'label' => ' 详情',
//                'icon' => '<i class="fa fa-file-o"></i>',
                'attr' => array(
                    'href' => getUrl('member/consumer/details?id='.$v['id']),
                    'class' => 'btn btn-xs green-stripe default',
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'member',
                    'key' => 'consumer-details'
                )
            ));
            $data['aaData'][$k][] = $btnConfig;
        }

        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 获取数据列表
     * @param int $page
     * @param int $pageNumber
     * @return array
     */
    public function lists($page = 0, $pageNumber = 0){
        $time = trim(get('time'));
        $status = trim(get('status'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if (!$time){
            $time =  dateFormat(time());
        }
        $time = strtotime($time);
        $e = strtotime('+1 day', $time);
        if ($status){
            $status = explode(',', $status);
            if (in_array('6', $status)){
                $status[] = 7;
            }
            $this->db->where_in('o.status', $status);
        }

        if($iSortCol_0 == 4){
            $this->db->order_by('o.product_amount', $sSortDir_0); // 商品总价
        }else if($iSortCol_0 == 5){
            $this->db->order_by('o.shipping_fee', $sSortDir_0); // 物流价格
        }else if($iSortCol_0 == 6){
            $this->db->order_by('o.total_amount', $sSortDir_0); // 订单总价
        }else if($iSortCol_0 == 8){
            $this->db->order_by('o.addtime', $sSortDir_0); // 下单日期
        }else{
            $this->db->order_by('o.addtime desc'); // 下单日期
        }
        $this->db->select('o.id,o.code,u.mobile,(o.product_amount+o.lunch_box_fee) as product_amount,o.total_amount,o.reality_amount,(o.bonus+o.postal_card+o.merchant_discount) as discount,
            o.shipping_fee,o.addtime,o.expense_type,o.status')
            ->join($this->mConsumer->tbUser.' u', 'o.consumer_id=u.id')
            ->where('o.addtime >=', $time)
            ->where('o.addtime <', $e);
        if($page > 0 && $pageNumber > 0){
            $tA = $this->mOrder->appPage($this->mOrder->tbOrder.' o', $page, false, $pageNumber);
            return $tA['list'];
        }else{
            return $this->mOrder->pagination($this->mOrder->tbOrder.' o');
        }
    }

    /**
     * 新规则
     * @param int $page
     * @param int $pageNumber
     * @return array
     */
    public function newlists($page = 0, $pageNumber = 0){
        $time = trim(get('time'));
        $status = trim(get('status'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if (!$time){
            $s =  dateFormat(time());
        }
        $s = strtotime($time);
        $e = strtotime('+1 day', $s);

        //获取在指定时间之前未下过单的用户
        $this->db->select("u.id");
        $this->db->from("consumer u");
        $this->db->join("consumer_order co","u.id = co.consumer_id AND co.merchant_take_time < ".$s,"left");
        $this->db->WHERE("co.id is NULL");
        $this->db->group_by("u.id");

        $temp = $this->db->get_compiled_select();
        $this->db->reset_query();

        if($iSortCol_0 == 4){
            $this->db->order_by('o.product_amount', $sSortDir_0); // 商品总价
        }else if($iSortCol_0 == 5){
            $this->db->order_by('o.shipping_fee', $sSortDir_0); // 物流价格
        }else if($iSortCol_0 == 6){
            $this->db->order_by('o.total_amount', $sSortDir_0); // 订单总价
        }else if($iSortCol_0 == 8){
            $this->db->order_by('o.addtime', $sSortDir_0); // 下单日期
        }else{
            $this->db->order_by('o.addtime desc'); // 下单日期
        }

        $this->db->select('o.id,o.code,u.mobile,(o.product_amount+o.lunch_box_fee) as product_amount,o.total_amount,o.reality_amount,(o.bonus+o.postal_card+o.merchant_discount) as discount,
            o.shipping_fee,o.addtime,o.expense_type,o.status')
            ->join($this->mConsumer->tbUser.' u', 'o.consumer_id=u.id');
        $this->db->join("(".$temp.") te","o.consumer_id = te.id");
        $this->db->where("IF(o.`status` =7 OR o.`status` = 8,
                        (o.addtime >= {$s} AND o.addtime < {$e} and o.`status` in (7,8)),
                        (o.merchant_take_time >= {$s} AND o.merchant_take_time < {$e} and o.`status` in (3,4,5,6) ))");
        if($status){
            $this->db->where_in('o.status',explode(',',$status));
        }
        if($page > 0 && $pageNumber > 0){
            $tA = $this->mOrder->appPage($this->mOrder->tbOrder.' o', $page, false, $pageNumber);
            return $tA['list'];
        }else{
            return $this->mOrder->pagination($this->mOrder->tbOrder.' o');
        }
    }

    /**
     * 首次下单用户
     * @param bool $all
     * @return array
     */
    public function firstUserlist($all=false){
        $time = trim(get('time'));
        if (!$time){
            $s =  dateFormat(time());
        }
        $s = strtotime($time);
        $e = strtotime('+1 day', $s);
        //获取在指定时间之前未下过单的用户
        $this->db->select("u.id");
        $this->db->from("consumer u");
        $this->db->join("consumer_order co","u.id = co.consumer_id AND co.merchant_take_time < ".$s,"left");
        $this->db->WHERE("co.id is NULL");
        $this->db->group_by("u.id");
        $temp = $this->db->get_compiled_select();
        $this->db->reset_query();

        $this->db->select('u.id,u.portrait,u.nickname,u.realname,u.mobile,u.balance,u.gender,u.addtime,u.last_login_time,u.status,o.addtime as orderTime');
        $this->db->join($this->mConsumer->tbUser.' u', 'o.consumer_id=u.id');
        $this->db->join("(".$temp.") te","o.consumer_id = te.id");
        if ($time){
            $this->db->where('o.merchant_take_time  > '.$s);
            $this->db->where('o.merchant_take_time  < '.$e);
        }
        $this->db->order_by("o.merchant_take_time asc");
        $this->db->group_by("u.id");
        if($all){
            return $tA = $this->mOrder->getAll($this->mOrder->tbOrder.' o');
        }else{
            return $this->mOrder->pagination($this->mOrder->tbOrder.' o');
        }
    }

    /**
     * 新用户列表
     * @param bool $all
     * @return array
     */
    public function newUserlist($all=false){
        $time = trim(get('time'));
        if (!$time){
            $s =  dateFormat(time());
        }
        $s = strtotime($time);
        $e = strtotime('+1 day', $s);
        if ($time){
            $this->db->where('addtime > '.$s);
            $this->db->where('addtime < '.$e);
        }
        $this->db->select("u.id,u.portrait,u.nickname,u.realname,u.mobile,u.balance,u.gender,u.addtime,u.last_login_time,u.status");
        $this->db->where(array('status >' => 0));
        if($all){
            return $tA = $this->mOrder->getAll($this->mOrder->tbUser.' u');
        }else{
            return $this->mOrder->pagination($this->mOrder->tbUser.' u');
        }
    }

    /**
     * 导出
     */
    public function export(){
        $filename = '新用户统计'.date('Y-m-d',time()).'.csv';
        header("Content-type:text/csv");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo mb_convert_encoding('ID,订单号,会员手机,商品总价,物流价格,实付金额,订单优惠,下单日期','gb2312','utf-8')."\n";
        $pageNumber = 500;
        $page = 1;
        $sTime = trim(get('time'));
        $status = trim(get('status'));
        $ss = strtotime($sTime);
        $order = $this->countNewUserOrders($ss);
        while(true){
            $list = $this->newlists($page,$pageNumber);
            if(empty($list)){
                break;
            }
            $page ++;
            foreach($list as $v){
                $shipping_fee = isset($v['shipping_fee']) ? $v['shipping_fee'] : 0;
                $addtime = dateFormat($v['addtime'], true);
                echo mb_convert_encoding($v['id']."\t".','.$v['code']."\t".','.$v['mobile']."\t".','.$v['product_amount']."\t".','.$shipping_fee."\t".','.$v['reality_amount']."\t".','.$v['discount']."\t".','.$addtime, 'gb2312','utf-8')."\n";
            }
        }
        /*【选择时间:2018-05-03】 【状态：待支付】 【新增用户：0】 【首次下单数：0】 【下单用户数：2】
         * 【订单总量：16】 【客单价：8.00】 【总金额：147.00】 【售后订单：0】 【售后订单总金额：0】
         * */
        $str = '';
        if (empty($status)){
            $status = explode(',', $status);
            $str = ' 【状态：';
            foreach ($status as $s){
                $str .= $this->mOrder->status($s).'、';
            }
            $str = trim($str, '、');
            $str .= '】';
        }
        echo mb_convert_encoding('【选择时间：' . $sTime . '】' . $str . ' 【新增注册用户数：' . $order['total_consumer'] . '】' .
                ' 【首次下单用户数：' . $order['total_user'] . '】' . ' 【新用户订单总量：' . $order['total_order'] . '】' . ' 【新用户关闭订单数：' . $order['close_order'] . '】' .
                ' 【新用户客单价：' . $order['single_amount'] . '】' . ' 【新用户订单总额：' . $order['total_amount'] . '】' .
                ' 【新用户订单实付总额：' . $order['reality_amount'] . '】' , 'gb2312','utf-8')."\n";
    }
}
